package cn.mesmile.message.model.email.entity;

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 线程池管理类
 */
public class ThreadPools {

    static final int PROCESSORS = Runtime.getRuntime().availableProcessors();

    /**
     * 样例线程池
     */
    public static final ThreadPoolExecutor exampleExecutor = new ThreadPoolExecutor(
            4 , PROCESSORS * 8,
            0L, TimeUnit.MILLISECONDS,
            new LinkedBlockingQueue<Runnable>(),
            new NameableThreadFactory("example"));

    /**
     * 自定义名称线程工厂
     * 基于 {@link java.util.concurrent.Executors.DefaultThreadFactory} 进行修改
     */
    private static class NameableThreadFactory implements ThreadFactory {

        private final ThreadGroup group;
        private final AtomicInteger threadNumber = new AtomicInteger(1);
        private final String namePrefix;

        public NameableThreadFactory(String name) {
            SecurityManager s = System.getSecurityManager();
            this.group = s != null ? s.getThreadGroup() : Thread.currentThread().getThreadGroup();
            if (name != null && !"".equals(name.trim())) {
                this.namePrefix = "pool-" + name + "-thread-";
            } else {
                this.namePrefix = "pool-default-thread-";
            }
        }

        @Override
        public Thread newThread(Runnable runnable) {
            Thread t = new Thread(this.group, runnable, this.namePrefix + this.threadNumber.getAndIncrement(), 0L);
            if (t.isDaemon()) {
                t.setDaemon(false);
            }
            if (t.getPriority() != Thread.NORM_PRIORITY) {
                t.setPriority(Thread.NORM_PRIORITY);
            }
            return t;
        }

    }

}